package br.ufpe.cin.msc.jrsj2.recommender.message;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;

import br.ufpe.cin.msc.jrsj2.recommender.persistence.domain.Program;

public class OntologyServiceMessage extends ApplicationMessage {

	private Program program;
	private List<String> genres;
	private StringBuffer elementValue;
	private String parentElement;

	public OntologyServiceMessage(String programTitle) {
		program = new Program();
		genres = new ArrayList<String>();
		program.setTitle(programTitle);
		elementValue = new StringBuffer();
		parentElement = null;
	}

	@Override
	protected void parseMessageElement(String uri, String localName,
			String qName, Attributes attributes) {
		if (qName.equals("category")
				&& attributes.getValue("type").equals("genre"))
			genres.add(attributes.getValue("key"));

		if (parentElement == null)
			parentElement = qName;
	}

	@SuppressWarnings("rawtypes")
	@Override
	public void buildResponseMessage(List objects) {
	}

	@Override
	protected void parseMessageContent(char[] ch, int start, int length) {
		elementValue.append(ch, start, length);
	}

	@Override
	protected void parseMessageEndElement(String uri, String localName,
			String qName) {
		if (parentElement != null) {
			if (parentElement.equals("programme") && qName.equals("title")) {
				program.setAlternativeTitle(elementValue.toString().trim());
				parentElement = null;
			}
		}
		if (qName.equals("programme"))
			program.setGenres(genres);
		elementValue.delete(0, elementValue.length());
	}

	public Program getProgramInstance() {
		return this.program;
	}

}
